/* 
 * Copyright (C) 2004-2005 Jonathan Bindel
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;

using DCSharp.Backend.Protocols;

namespace DCSharp.Backend.Connections
{
	public sealed class UdpServer : Server
	{
		private static UdpServer instance;
		private static Socket socket;

		private IProtocol protocol;

		private byte[] buffer;
		private AsyncCallback receivedData;

		public UdpServer(IPAddress localIP, int port, IProtocol protocol) :
			base(localIP, port)
		{
			if (protocol == null)
			{
				throw new ArgumentNullException("protocol");
			}
			this.protocol = protocol;

			buffer = new byte[40096];
			receivedData = new AsyncCallback(OnReceivedData);
		}

		#region Methods

		public static void StartListening(int port, IProtocol protocol)
		{
			StopListening();

			instance = new UdpServer(IPAddress.Any, port, protocol);
			instance.Start();
		}

		public static void StopListening()
		{
			if (instance != null)
			{
				instance.Stop();
				instance = null;
			}
		}

		protected override void ServerStart()
		{
			Listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
				ProtocolType.Udp);
			Listener.Bind(new IPEndPoint(LocalIP, Port));

			BeginReceive();
		}

		private void BeginReceive()
		{
			Listener.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
				receivedData, Listener);
		}

		private void OnReceivedData(IAsyncResult result)
		{
			Socket socket = (Socket)result.AsyncState;
			int length = 0;

			try
			{
				length = socket.EndReceive(result);
			}
			catch (ObjectDisposedException)
			{
			}

			if (length > 0)
			{
				string message = protocol.Encoding.GetString(buffer, 0, length);
				try
				{
					protocol.Handle(message);
				}
				catch
				{
				}
				BeginReceive();
			}
		}

		public static void Send(EndPoint endPoint, string message)
		{
			Send(endPoint, message, Encoding.UTF8);
		}

		public static void Send(EndPoint endPoint, string message,
			Encoding encoding)
		{
			try
			{
				if (socket == null)
				{
					socket = new Socket(AddressFamily.InterNetwork,
						SocketType.Dgram, ProtocolType.Udp);
				}
				socket.SendTo(encoding.GetBytes(message), endPoint);
			}
			catch (Exception e)
			{
				Debug.WriteLine(e);
			}
		}

		public static void CloseSockets()
		{
			if (socket != null)
			{
				socket.Close();
				socket = null;
			}
		}

		#endregion
	}
}
